//
//  HomePageViewController.m
//  HuaRun
//
//  Created by admin on 17/8/28.
//  Copyright © 2017年 Sunny. All rights reserved.
//

#import "HomePageViewController.h"
#import "Home_ContactHistoryCell.h"
#import "Home_MeetingHistoryCell.h"
#import "Home_BirthCell.h"
#import "ImageLabView.h"
#import "Home_CompanyHistoryModel.h"
#import "Home_MeetingHistoryModel.h"
#import "Home_ContactHistoryModel.h"
#import "Home_BirthModel.h"
#import "Home_SettingViewController.h"
#import "Home_SearchViewController.h"
#import "Contact_DetailViewController.h"
#import "Meeting_DetailViewController2.h"
#import "Company_DetailViewController2.h"
#import "Home_Search_NoteCell.h"
#
@interface HomePageViewController ()


//公司
@property (nonatomic, strong) UIButton * companyView;
//联系人
@property (nonatomic, strong) UIButton * contactView;
//会议
@property (nonatomic, strong) UIButton * meetingView;
//最近查看
@property (nonatomic, strong) UIView * historyView;
//最近生日
@property (nonatomic, strong) UIView * birthView;

@end

@implementation HomePageViewController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
//    [self changHistoryType:0];
}
    
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _historyType = -1;
    self.navigationItem.title = NSLocalizedString(@"system_name", nil);
    self.searchView.backgroundColor = RGBA(249, 249, 249, 1);
    self.searchView.placeholderStr = NSLocalizedString(@"请输入关键字搜索", nil);

//    self.tableView.scrollEnabled = NO;
    self.tableView.bounces = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = RGBA(249, 249, 249, 1);

    [self.tableView registerClass:[Home_ContactHistoryCell class]
           forCellReuseIdentifier:@"Home_ComanyHistoryCell"];
    [self.tableView registerClass:[Home_BirthCell class]
           forCellReuseIdentifier:@"Home_BirthCell"];
    [self.tableView registerClass:[Home_MeetingHistoryCell class]
           forCellReuseIdentifier:@"Home_MeetingHistoryCell"];
    [self.tableView registerClass:[Home_Search_NoteCell class]
           forCellReuseIdentifier:@"Home_Search_NoteCell"];

    weakself(ws);
    [self nbRightImageName:@"个人中心" title:nil taget:self clickBlock:^(id result) {
        [ws pushUserSettingPage];
    }];

    [self changHistoryType:0];
    [self fetchRencentBirthList];

//    self.searchView.textField.delegate =self;
    [self.searchView.textField addTarget:self action:@selector(pushSearchPage) forControlEvents:(UIControlEventTouchDown)];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        //若没数据，显示1个，记录为空
        if (_isNoneHistory) {
            return 1;
        }
        //最多显示5个
        return self.dataArray.count > 5 ? 5 : self.dataArray.count;
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (_isNoneHistory) {
            Home_Search_NoteCell * cell = [tableView dequeueReusableCellWithIdentifier:@"Home_Search_NoteCell"
                                                                          forIndexPath:indexPath];
            cell.valueLab1.text = NSLocalizedString(@"暂无数据", nil);

            return cell;
        }
        
        if ( _historyType == LookHistoryTypeContact) {
            
            Home_ContactHistoryCell * cell = [tableView dequeueReusableCellWithIdentifier:@"Home_ComanyHistoryCell"
                                                                            forIndexPath:indexPath];
            cell.contactHisModel = self.dataArray[indexPath.row];
            return cell;
        }

        Home_MeetingHistoryCell * cell = [tableView dequeueReusableCellWithIdentifier:@"Home_MeetingHistoryCell"
                                                                        forIndexPath:indexPath];
        if (_historyType == LookHistoryTypeCompany) {
            cell.companyHisModel = self.dataArray[indexPath.row];
        }else {
            cell.meetingHisModel = self.dataArray[indexPath.row];
        }

        return cell;

    }
    if (_birthArray.count == 0) {
        Home_Search_NoteCell * cell = [tableView dequeueReusableCellWithIdentifier:@"Home_Search_NoteCell"
                                                                      forIndexPath:indexPath];
        cell.valueLab1.text = NSLocalizedString(@"暂无数据", nil);
        return cell;
    }

    Home_BirthCell * cell = [tableView dequeueReusableCellWithIdentifier:@"Home_BirthCell"
                                                                    forIndexPath:indexPath];
    cell.dataArray = _birthArray;
    weakself(ws);
    cell.clickBlock = ^(NSString * idStr) {
        NSLog(@"click %@", idStr);
        Contact_DetailViewController * meetingVC = [[Contact_DetailViewController alloc] init];
        
        meetingVC.contactId = idStr;
        meetingVC.hidesBottomBarWhenPushed = YES;
        [ws.navigationController pushViewController:meetingVC animated:YES];
    };
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1 && _birthArray.count == 0) {
        return 44;
    }
    return 50;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    if (indexPath.section == 0) {
        if (self.dataArray.count <= 0) {
            return;
        }
        
        //如果是公司
        if ( _historyType == LookHistoryTypeCompany) {
            
            Home_CompanyHistoryModel * companyHisModel = self.dataArray[indexPath.row];
            [self pushCompanyDetailPageWithId:companyHisModel.id];
            
        }else if (_historyType == LookHistoryTypeContact) {

            Home_ContactHistoryModel * contactHisModel = self.dataArray[indexPath.row];
            
            [self pushContacDetailPageWithId:contactHisModel.contactId];
            
        }else if (_historyType == LookHistoryTypeMeeting) {
            
            Home_MeetingHistoryModel * meetingHisModel = self.dataArray[indexPath.row];
            [self pushMeetingDetailPageWithId:meetingHisModel.id];
        
        }else {
            
        }
        
    }else if (indexPath.section == 1) {
        if (_birthArray.count <= 0) {
            return;
        }
        
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        
        self.historyView = [self makeHistoryView];
        return _historyView;
    
    }else if (section ==1) {
        
        self.birthView = [self makeCommonSectionHeaderViewWithText:NSLocalizedString(@"最近生日", nil)
                 imageName:@"生日"
                 imageSize:(CGSizeMake(20, 20))];
        return _birthView;
    }
    return [UIView new];
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return section == 0 ? 100 : 60;
}

//进入联系人详情页
- (void)pushContacDetailPageWithId:(NSString *)idStr {
    Contact_DetailViewController * meetingVC = [[Contact_DetailViewController alloc] init];
    meetingVC.hidesBottomBarWhenPushed = YES;
    meetingVC.contactId = idStr;
    [self.navigationController pushViewController:meetingVC animated:YES];
    
}

//进入会议详情
- (void)pushMeetingDetailPageWithId:(NSString *)idStr {
    
    Meeting_DetailViewController2 * detailVC = [Meeting_DetailViewController2 new];
    detailVC.meetingId = idStr;
    detailVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detailVC animated:YES];
}

//进入公司详情
- (void)pushCompanyDetailPageWithId:(NSString *)idStr {
    Company_DetailViewController2 * detailVC = [Company_DetailViewController2 new];
    detailVC.accountId = idStr;
    detailVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detailVC animated:YES];
}

#pragma mark 网络请求
//获取公司记录
- (void)fetchCompanyHistory {
    NSString * url = [NSString stringWithFormat:@"%@%@", kBaseUrl,
                      kHome_CompanyHistoryUrl];
    
    NSDictionary * dic = @{@"type": @"0"};
    weakself(ws);
    [self showActivity:kLodingStr];
    [NetWorkHelper getWithURLString:url parameters:dic success:^(id object) {
        [ws hideAllAlert];
        
        if (![object[@"code"] isEqual: kSuccessCode]) {
            NSString * info = [NSString isemptyStr:object[@"msg"]] ? kUnknownError : object[@"msg"];
            [ws showWithText:info];
            return;
        }
        NSArray * array = [NSArray yy_modelArrayWithClass:[Home_CompanyHistoryModel class] json:object[@"list"]];

        ws.dataArray = array;
        
        ws.isNoneHistory = ws.dataArray.count == 0;
//        [ws.tableView reloadSections:[NSIndexSet indexSetWithIndex:0]
//                      withRowAnimation:(UITableViewRowAnimationNone)];
        [ws.tableView reloadData];
        
        ws.companyView.userInteractionEnabled = YES;
        ws.contactView.userInteractionEnabled = YES;
        ws.meetingView.userInteractionEnabled = YES;

    } failure:^(NSError *error) {
        [ws hideAllAlert];

        [ws showAlert:kNetworkError];
    }];
}

//获取联系人记录
- (void)fetchContactHistory {
    NSString * url = [NSString stringWithFormat:@"%@%@", kBaseUrl,
                      kHome_ContactHistoryUrl];
    
    NSDictionary * dic = @{@"type": @"0"};
    weakself(ws);
    
    [self showActivity:kLodingStr];
    [NetWorkHelper getWithURLString:url parameters:dic success:^(id object) {
        [ws hideAllAlert];

        if (![object[@"code"] isEqual: kSuccessCode]) {
            NSString * info = [NSString isemptyStr:object[@"msg"]] ? kUnknownError : object[@"msg"];
            [ws showWithText:info];
            return;
        }
        NSArray * array = [NSArray yy_modelArrayWithClass:[Home_ContactHistoryModel class] json:object[@"list"]];
        
        ws.dataArray = array;
        
        ws.isNoneHistory = ws.dataArray.count == 0;
//        [ws.tableView reloadSections:[NSIndexSet indexSetWithIndex:0]
//                    withRowAnimation:(UITableViewRowAnimationNone)];
        [ws.tableView reloadData];
        ws.companyView.userInteractionEnabled = YES;
        ws.contactView.userInteractionEnabled = YES;
        ws.meetingView.userInteractionEnabled = YES;

    } failure:^(NSError *error) {
        [ws hideAllAlert];

        [ws showWithText:kNetworkError];
        
    }];
}

//获取会议记录
- (void)fetchMeetingHistory {
    NSString * url = [NSString stringWithFormat:@"%@%@", kBaseUrl,
                      kHome_MeetingHistoryUrl];
    
    NSDictionary * dic = @{@"type": @"0"};
    weakself(ws);
    [self showActivity:kLodingStr];
    [NetWorkHelper getWithURLString:url parameters:dic success:^(id object) {
        [ws hideAllAlert];
        if (![object[@"code"] isEqual: kSuccessCode]) {
            NSString * info = [NSString isemptyStr:object[@"msg"]] ? kUnknownError : object[@"msg"];
            [ws showWithText:info];
            return;
        }
        NSArray * array = [NSArray yy_modelArrayWithClass:[Home_MeetingHistoryModel class] json:object[@"list"]];
        
        ws.dataArray = array;
        
        ws.isNoneHistory = ws.dataArray.count == 0;
//        [ws.tableView reloadSections:[NSIndexSet indexSetWithIndex:0]
//                    withRowAnimation:(UITableViewRowAnimationNone)];
        [ws.tableView reloadData];
        ws.companyView.userInteractionEnabled = YES;
        ws.contactView.userInteractionEnabled = YES;
        ws.meetingView.userInteractionEnabled = YES;

    } failure:^(NSError *error) {
        [ws hideAllAlert];

        [ws showWithText:kNetworkError];
        
    }];

}
- (NSString *)getCurrentMonth {
    // 获取代表公历的NSCalendar对象
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    // 获取当前日期
    NSDate* dt = [NSDate date];
    // 定义一个时间字段的旗标，指定将会获取指定年、月、日、时、分、秒的信息
    unsigned unitFlags = NSCalendarUnitYear |
    NSCalendarUnitMonth |  NSCalendarUnitDay |
    NSCalendarUnitHour |  NSCalendarUnitMinute |
    NSCalendarUnitSecond | NSCalendarUnitWeekday;
    // 获取不同时间字段的信息
    NSDateComponents* comp = [gregorian components: unitFlags
                                          fromDate:dt];
    return [NSString stringWithFormat:@"%ld", comp.month];
}

//获取最近生日的人
- (void)fetchRencentBirthList {
    NSString * url = [NSString stringWithFormat:@"%@%@", kBaseUrl,
                      kHome_BirthListUrl];
//    [NSDate date];
    NSDictionary * dic = @{@"current": @"1",
                           @"size": @"6",
                           @"month": [self getCurrentMonth]};
    weakself(ws);
    [NetWorkHelper getWithURLString:url parameters:dic success:^(id object) {
        if (![object[@"code"] isEqual: kSuccessCode]) {
            NSString * info = [NSString isemptyStr:object[@"msg"]] ? kUnknownError : object[@"msg"];
            [ws showWithText:info];

            return;
        }
        NSArray * array = [NSArray yy_modelArrayWithClass:[Home_BirthModel class] json:object[@"list"]];
        ws.birthArray = array;
        
//        ws.isNoneHistory = ws.dataArray.count == 0;
//        [ws.tableView reloadSections:[NSIndexSet indexSetWithIndex:1]
//                    withRowAnimation:(UITableViewRowAnimationNone)];
        [ws.tableView reloadData];

    } failure:^(NSError *error) {
        [ws showWithText:kNetworkError];
        
    }];
}

#pragma mark 方法、封装的视图
//进入个人中心页面
- (void)pushUserSettingPage {
    Home_SettingViewController * settingVC = [Home_SettingViewController new];
    
    settingVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:settingVC animated:YES];
}
    //进入搜索页面
- (void)pushSearchPage {
    Home_SearchViewController * settingVC = [Home_SearchViewController new];
    settingVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:settingVC animated:YES];
}

- (void)methodBind {
    UITapGestureRecognizer * tapGesture1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapMethod:)];
    UITapGestureRecognizer * tapGesture2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapMethod:)];
    UITapGestureRecognizer * tapGesture3 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapMethod:)];

    self.companyView.userInteractionEnabled = YES;
    self.contactView.userInteractionEnabled = YES;
    self.meetingView.userInteractionEnabled = YES;
    
    [self.companyView addGestureRecognizer:tapGesture1];
    [self.contactView addGestureRecognizer:tapGesture2];
    [self.meetingView addGestureRecognizer:tapGesture3];
    
}

- (void)tapMethod:(UITapGestureRecognizer *)tap {
    UIView * view = tap.view;
    NSLog(@"view %@", view);
    self.companyView.userInteractionEnabled = NO;
    self.contactView.userInteractionEnabled = NO;
    self.meetingView.userInteractionEnabled = NO;

    if (view  == _companyView) {
        
        [self changHistoryType:0];
    }else if (view == _contactView) {
        
        [self changHistoryType:1];
    }else if (view == _meetingView) {
    
        [self changHistoryType:2];
    }
}

//切换最近查看的记录
- (void)changHistoryType:(int)type {
    if (_historyType == type) {
        self.companyView.userInteractionEnabled = YES;
        self.contactView.userInteractionEnabled = YES;
        self.meetingView.userInteractionEnabled = YES;

        return;
    }
    
    _historyType = type;

    _companyView.selected = NO;
    _contactView.selected = NO;
    _meetingView.selected = NO;

    if (type == 0) {
        
        _companyView.selected = YES;
        [self fetchCompanyHistory];
    
    }else if (type == 1) {
        
        _contactView.selected = YES;
        [self fetchContactHistory];
        
    }else if (type == 2) {
        
        _meetingView.selected = YES;
        [self fetchMeetingHistory];
    }
}

- (UIView *)makeHistoryView {
    UIView * view = [UIView new];
    view.frame = CGRectMake(0, 0, kMainScreenWidth, 100);
    view.backgroundColor = RGBA(249, 249, 249, 1);

    UIView * titleView = [self makeCommonSectionHeaderViewWithText:NSLocalizedString(
                                                                                     @"最近查看", nil)
                                                         imageName:@"最近查看"
                          imageSize:(CGSizeMake(15, 10))];
    titleView.tag = 200;
    [view addSubview:titleView];
    
    [view addSubview:self.contactView];
    [view addSubview:self.companyView];
    [view addSubview:self.meetingView];
    
    weakself(ws);
    CGFloat width = ( kMainScreenWidth - kMargin10 * 4) / 3;
    [self.contactView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(titleView.mas_bottom).offset(kMargin10);
        make.centerX.mas_equalTo(view);
        make.width.mas_equalTo(width);
        make.height.mas_equalTo(35);
    }];
    
    [self.companyView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(ws.contactView);
        make.left.mas_equalTo(view).offset(kMargin10);
        make.width.height.mas_equalTo(ws.contactView);
    }];
    
    [self.meetingView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(ws.contactView);
        make.right.mas_equalTo(view).offset(-kMargin10);
        make.width.height.mas_equalTo(ws.contactView);
    }];
    return view;
}
    

- (UIButton *)makeCommonButtonWithText:(NSString *)text
                           normalImage:(NSString *)normalImage
                         selectedImage:(NSString *)selectedImage {
    
    UIButton * btn = [UIButton new];
    [btn setImage:[UIImage imageNamed:normalImage] forState:(UIControlStateNormal)];
    [btn setImage:[UIImage imageNamed:selectedImage] forState:(UIControlStateSelected)];
    [btn setTitleColor:[UIColor colorWithHex:@"3c3c3c"] forState:(UIControlStateNormal)];
    [btn setTitleColor:RGBA(243, 161, 50, 1) forState:(UIControlStateSelected)];
//    btn.backgroundColor = [UIColor redColor];
    [btn setTitle:text forState:UIControlStateNormal];
    [btn setTitle:text forState:UIControlStateSelected];
    [btn.titleLabel setFont:kGeneralFontSize];
    [btn centerButtonAndImageWithSpacing:kMargin10];
    return btn;
}

- (UIView *)makeCommonSectionHeaderViewWithText:(NSString *)text
                                      imageName:(NSString *)imageName
                                      imageSize:(CGSize)imageSize{
    
    UIView * view = [[UIView alloc] initWithFrame:(CGRectMake(0, 0, kMainScreenWidth, 50))];
    view.backgroundColor = RGBA(249, 249, 249, 1);
    
    UIImageView * imageView = [[UIImageView alloc] init];
    imageView.image = [UIImage imageNamed:imageName];
    [view addSubview:imageView];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(imageSize);
        make.centerY.mas_equalTo(view);
        make.left.mas_equalTo(view).offset(kMargin10);
    }];
    
    UILabel * label = [[UILabel alloc] init];
    label.font = kFontSize15;
    label.text = text;
    label.textColor = [UIColor colorWithHex:@"3c3c3c"];
    label.tag = 100;
    [view addSubview:label];
    
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(imageView.mas_right).offset(kMargin10);
        make.centerY.mas_equalTo(view);
        make.size.mas_equalTo(CGSizeMake(150, 20));
    }];
    return view;
    
}

- (UIView *)makeCommonView2WithText:(NSString *)text
                          imageName:(NSString *)imageName
                          imageSize:(CGSize)imageSize{
    
    UIView * view = [[UIView alloc] initWithFrame:(CGRectMake(0, 0, kMainScreenWidth, 50))];
    view.backgroundColor = kRandomColor;// RGBA(249, 249, 249, 1);
    
    UIImageView * imageView = [[UIImageView alloc] init];
    imageView.image = [UIImage imageNamed:imageName];
    [view addSubview:imageView];
    
    UILabel * label = [[UILabel alloc] init];
    label.font = kGeneralFontSize;
    label.text = text;
    label.textColor = [UIColor colorWithHex:@"3c3c3c"];
    label.tag = 100;
    [view addSubview:label];

    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(imageSize);
        make.centerY.mas_equalTo(view);
        make.left.mas_equalTo(view).offset(0);
    }];
    
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(imageView.mas_right).offset(kMargin10);
        make.height.centerY.right.mas_equalTo(view);
    }];
    return view;
    
}
#pragma mark getter setter
- (UIButton *)contactView {
    if (!_contactView) {
        self.contactView = [self makeCommonButtonWithText:NSLocalizedString(@"联系人", nil)
                                            normalImage:@"icon_button_contact01"
                                          selectedImage:@"联系人-选中"];
    }
    return _contactView;
}

- (UIButton *)meetingView {
    if (!_meetingView) {
        self.meetingView = [self makeCommonButtonWithText:NSLocalizedString(@"会议", nil)
                                            normalImage:@"icon_button_meeting01"
                                          selectedImage:@"会议-选中"];
    }
    return _meetingView;
}

- (UIButton *)companyView {
    if (!_companyView) {
        self.companyView = [self makeCommonButtonWithText:NSLocalizedString(@"公司", nil)
                                            normalImage:@"icon_button_company01"
                                          selectedImage:@"公司-选中"];
    }
    return _companyView;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (void)resetLabelLanguge {
    self.navigationItem.title = NSLocalizedString(@"system_name", nil);
    self.searchView.placeholderStr = NSLocalizedString(@"请输入关键字搜索", nil);

    UIView * view1 = [_historyView viewWithTag:200];
    UILabel * label1 = [view1 viewWithTag:100];
    label1.text = NSLocalizedString(@"最近查看",nil);
    
    UILabel * label2 = [_birthView viewWithTag:100];
    label2.text = NSLocalizedString(@"最近生日",nil);
    
    NSString * companyText = NSLocalizedString(@"公司", nil);
    [_companyView setTitle:companyText forState:(UIControlStateNormal)];
    [_companyView setTitle:companyText forState:(UIControlStateSelected)];

    NSString * contactText = NSLocalizedString(@"联系人", nil);
    [_contactView setTitle:contactText forState:(UIControlStateNormal)];
    [_contactView setTitle:contactText forState:(UIControlStateSelected)];
    
    NSString * meetingText = NSLocalizedString(@"会议", nil);
    [_meetingView setTitle:meetingText forState:(UIControlStateNormal)];
    [_meetingView setTitle:meetingText forState:(UIControlStateSelected)];
    
}

@end
